package mango.utils;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class MCipher {
    private static final String SECRET_TYPE = "DES";
    
    public static byte[] randomKey() {
        try {
            SecureRandom sr = new SecureRandom();
            KeyGenerator kg = KeyGenerator.getInstance(SECRET_TYPE);
            kg.init(sr);
            SecretKey key = kg.generateKey();
            byte[] rawKeyData = key.getEncoded();
            return rawKeyData;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     * 
     * @return
     */
    public static byte[] encrypte(byte[] data, byte[] rawKeyData) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(rawKeyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_TYPE);
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(SECRET_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            byte[] encryptedData = cipher.doFinal(data);
            return encryptedData;
        }
        catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public static byte[] decrypte(byte[] encryptedData, byte[] rawKeyData) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(rawKeyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_TYPE);
            SecretKey key = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(SECRET_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            byte[] decryptedData = cipher.doFinal(encryptedData);
            return decryptedData;
        }
        catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }
}
